from django.forms.models import model_to_dict

from web import utils


tools = utils.Utils()


class Module:
    def __init__(self):
        pass

    # 返回用户数据格式
    def user_data_format(self, user):
        new_user = model_to_dict(user)

        # 时间
        new_user['create_time'] = tools.time_format(user.create_time)
        new_user['update_time'] = tools.time_format(user.update_time)

        # 头像
        if user.avatar:
            new_user['avatar'] = user.avatar.url
        else:
            new_user['avatar'] = '/media/user/avatar/default.jpg'

        # 删除密码
        del new_user['password']

        return new_user
    # 返回帖子数据格式
    def post_data_format(self, post, level=0, fields=0):
        """
        level: 
            - 0: 携带作者数据
        fields: 
            - 0: 不携带帖子详情
            - 1: 携带帖子详情
        """
        new_post = model_to_dict(post)
        # 封面
        if post.cover:
            new_post['cover'] = post.cover.url
        else:
            new_post['cover'] = ''
        new_post['create_time'] = tools.time_format(post.created_at)
        new_post['update_time'] = tools.time_format(post.updated_at)
        
        new_post['category'] = model_to_dict(post.category)

        if level == 0:
            new_post['user'] = self.user_data_format(post.user_id)

        if fields == 1:
            new_post['content'] = post.content
        else:
            # 取一些帖子详情的内容
            new_post['content'] = post.content[:100]
            # 判断是否为空
            if new_post['content'] == '':
                new_post['content'] = '暂无内容'
            # 判断有没有100个字
            if len(new_post['content']) >= 100:
                new_post['content'] = new_post['content'] + '...'

        # 删除帖子的user_id
        del new_post['user_id']
        return new_post
            



